<?php

namespace App\Models\Shop;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class Category extends Model
{
    //黑名单
    protected $guarded = [];

    /**
     * 表明模型是否应该被打上时间戳
     */
    public $timestamps = false;


    /**
     * 获取一级分类下的二级分类
     */
    public function children()
    {
        return $this->hasMany('App\Models\Shop\Category', 'parent_id', 'id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     * 分类有多个商品
     */
    public function products()
    {
        return $this->belongsToMany('App\Models\Shop\Product');
    }

    /**
     * 清除缓存
     */
    static function clear()
    {
        Cache::forget('shop_categories');
    }

    /**
     * 获取所有分类
     */
    static function get_categories()
    {
        //设置缓存,存在shop_categories下
        $categories = Cache::rememberForever('shop_categories', function () {
            return self::with([
                'children' => function ($query) {
                    $query->orderBy('sort_order');
                } //二级分类下的排序
            ])->where('parent_id', 0)->orderBy('sort_order')->get();
        });
        return $categories;
    }


    /**
     * 检查一级分类下是否有二级分类
     */
    static function check_children($id)
    {
        $category = self::with('children')->find($id);
        if ($category->children->isEmpty()) {
            return true;
        }
        return false;
    }

    /**
     * @param $id
     * @return bool
     * 判断分类下是否有商品
     */
    static function check_products($id)
    {
        $category = self::with('products')->find($id);
        if ($category->products->isEmpty()) {
            return true;
        }
        return false;
    }


    /**
     *搜索商品分类时，屏蔽掉没有商品的分类
     * 查出有商品的分类
     */
    static function filter_categories()
    {
        $categories = self::has('children.products')->with([
            'children' => function ($query) {
                $query->has('products');
            }
        ])->get();
        return $categories;
    }


}
